package com.ncmmall.mall.controller.securitys;

import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.application.securitys.user.UserApplication;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.feijin.commons.securitys.MD5HashUtils;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author tongchun
 *         系统用户管理
 */
@Controller
@RequestMapping(value = "/securitys")
public class InfoController {

    private final static Logger LOG = LoggerFactory.getLogger(InfoController.class);

    @Value("${web.domain}")
    private String webDomain;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private UserApplication userApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 用户信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    private String list(Model model) {

        WebUser user = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
        model.addAttribute("user", user);

        return "securitys/user/info";
    }

    /**
     * 修改基础信息（昵称、姓名、头像、邮箱、手机号、公司信息）
     *
     * @param requestWith
     * @param params
     * @return
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> updateInfo(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, WebUser params) {

        try {

            WebUser user = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
            user.setAvatar(params.getAvatar());
            user.setRealName(params.getRealName());
            user.setMobile(params.getMobile());
            userApplication.modify(user);

            logApplication.eventOfSystem(Securitys.currentUser(), "修改用户信息" + user.getUsername(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 跳转到修改密码
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.GET)
    public String modifyPasswords(Model model) {

        return "securitys/user/modifypassword";
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> modifyPassword(HttpServletRequest request, @RequestParam("oldPassword") String oldPassword, @RequestParam("password") String newPassword) {

        try {

            WebUser user = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
            String passwordAsMd5 = MD5HashUtils.asMD5(oldPassword, user.getUsername());
            if (user.getPassword().equals(passwordAsMd5)) {
                passwordAsMd5 = MD5HashUtils.asMD5(newPassword, user.getUsername());
                user.setPassword(passwordAsMd5);
                user.setAccessToken(MD5HashUtils.md5(passwordAsMd5, user.getUsername()));

                userApplication.modifyPassword(user, newPassword);

                logApplication.eventOfSystem(Securitys.currentUser(), "修改密码" + user.getUsername(), Securitys.getIp(request));

                Subject subject = SecurityUtils.getSubject();
                Securitys.unactivateUserSession();
                subject.logout();
                return ImmutableMap.of("status", true);

            } else {
                return ImmutableMap.of("status", false, "msm", "原密码不正确");
            }

        } catch (Exception e) {
            return ImmutableMap.of("status", false, "msm", "系统异常，请重试");
        }
    }

}
